Import mojo
Import agfx

Class TParticle
	Field X:Float, Y:Float, XD:Float, YD:Float
	Field Age:Float  = 1.0
	Field DecayRate:Float
	Field GravityX:Float = 0.0
	Field GravityY:Float =0.0

	Method New(x:Float, y:Float, Scatter)
		Self.X = x
		Self.Y = y
		Self.XD = Rnd(-Scatter, Scatter)
		Self.YD = Rnd(-Scatter, Scatter)
		Self.Age = Rnd()
		Self.DecayRate = Rnd(.005, .01)
	End Method

	Method Update()
		X += XD + GravityX
		Y += YD + GravityY
		If X < 0 Or X > DeviceWidth Then Age = 0
		If Y < 0 Or Y > DeviceWidth Then Age = 0
		Age -= DecayRate
	End Method

End Class

Class TParticleEmitter
	Field Particles:List<TParticle> = New List<TParticle>
	Field Scatter:Float, ParticleCount
	Field GravityX:Float = 0, GravityY:Float = 0
	Field ParticleImage:TImage
	Field RemainingParticles
	
	Method New(x:Float, y:Float, scatter:Float, particleCount, particleImage:TImage, gravX:Float, gravY:Float)
		GravityX = gravX
		GravityY = gravY
		For Local i = 0 To ParticleCount	
			Particles.AddLast(New TParticle(x, y, scatter))
		Next
		Self.ParticleImage = particleImage
		RemainingParticles = particleCount
	End Method
	
	Method Update()
		Local LiveParticles:= New List<TParticle>
		Local p:TParticle

		For p = Eachin Particles
			p.GravityX = GravityX
			p.GravityY = GravityY
			p.Update()
			If p.Age > 0 Then LiveParticles.AddLast(p)
		Next
		Particles = LiveParticles
		RemainingParticles = Particles.Count
	End Method
	
	Method Render()
		Local p:TParticle
		For p = Eachin Particles
			SetAlpha p.Age
			SetBlend LightenBlend
			SetColor Rnd(100,255), Rnd(100,255), Rnd(100,255) 			
			ParticleImage.Draw(p.X, p.Y,0,p.Age, p.Age)
		Next
	End Method

End Class

Class TParticleManager
	
	Field ParticleEmitters:List<TParticleEmitter> = New List<TParticleEmitter>
	Field TotalParticles = 0
	
	Method AddParticleEmitter(x:Float, y:Float, scatter:Float, particleCount, particleImage:TImage, gravX:Float, gravY:Float)
		ParticleEmitters.AddLast( New TParticleEmitter ( x, y, scatter, particleCount, particleImage, gravX, gravY ) )
	End Method
	
	Method Update()
		Local LivePE:List<TParticleEmitter> = New List<TParticleEmitter>
		Local pe:TParticleEmitter
		TotalParticles = 0
		For pe = Eachin ParticleEmitters
			pe.Update()
			If pe.RemainingParticles > 0 
				LivePE.AddLast(pe)
				TotalParticles += pe.RemainingParticles
			End If
		Next
		ParticleEmitters = LivePE

	End Method

	Method Render()
		Local pe:TParticleEmitter
		For pe = Eachin ParticleEmitters
			pe.Render()
		Next
	End Method


End Class